package com.sanri.tools.modules.core;

import com.sanri.tools.modules.core.service.cc.CommonConfigService;
import com.sanri.tools.modules.core.service.connect.FileBaseConnectService;
import com.sanri.tools.modules.core.service.connect.dtos.ConnectInput;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Collection;

/**
 * 初始化数据
 * httprequest 文件初始化, 一些常用 http 接口文件初始化, 对应 connect.httprequest.template.http ; 需要开启 tools-proxy 模块才能使用
 * httpbind    文件初始化
 */
@Component
@Slf4j
public class InitAddConfig implements InitializingBean {
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private FileBaseConnectService fileBaseConnectService;

    @Autowired
    private CommonConfigService commonConfigService;

    @Override
    public void afterPropertiesSet() throws Exception {
//        Path initAddPath = new File("").toPath().resolve("initAddConfig");
//        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        ApplicationHome applicationHome = new ApplicationHome(getClass());
        File dir = new File(applicationHome.getSource().getParentFile(), "initAddConfig");
//        File dir = new File(path, "initAddConfig");
        if (!dir.exists() || !dir.isDirectory()){
            log.warn("没有配置初始化配置文件加载目录或者不是目录, 外部配置加载失败; 如需初始化加载, 请在 {} 路径下放置初始化配置", dir.getAbsolutePath());
            return ;
        }

        File lock = new File(dir, "lock");
        boolean newFile = lock.createNewFile();
        if (!newFile){
            log.warn("已经存在 lock 文件, 在目录[{}], 不再重新加载初始化配置", dir.getAbsolutePath());
            return ;
        }

        log.info("初始化新增配置位置: {}",dir.getAbsolutePath());
        Collection<File> files = FileUtils.listFiles(dir, FileFileFilter.FILE, TrueFileFilter.INSTANCE);
        if (files != null && files.size() > 0) {
            for (File file : files) {
                String name = file.getName();
                String[] split = StringUtils.split(name, ".");
                if (split.length != 4){
                    log.warn("[{}]文件名格式错误,预期 4 部分, 分别为 分组,模块,基础名,格式",name);
                    continue;
                }

                String mark = split[0];
                String module = split[1];
                String baseName = split[2];
                String format = split[3];

                String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
                if ("connect".equals(mark)){
                    ConnectInput connectInput = new ConnectInput(module, baseName, format, "/");
                    connectInput.setContent(content);
                    fileBaseConnectService.internalUpdateConnect(connectInput);
                }else if ("cc".equals(mark)){
                    commonConfigService.editFile(module+"."+format,baseName,content);
                }else {
                    log.error("不支持的文件标记: {}", mark);
                }
            }
        }
    }
}
